<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef" name="XlCustomerStoreInfoForm">
      <template #customerTypeCode="{ model, field }">
        <!-- <a-input @click="handleTypeOpen" v-model:value="model[field]" placeholder="请选择渠道" :allowClear="true"
           />
            -->
        <a-select v-model:value="model[field]" mode="tags" style="width: 100%" placeholder="请选择渠道"
          @click="handleTypeOpen" :default-active-first-option="false" :show-arrow="false" :filter-option="false"
          :open="false">
        </a-select>
      </template>


      <template #provinceSlot="{ model, field }" >
        <!-- <a-input @click="handleTypeOpen" v-model:value="model[field]" placeholder="请选择渠道" :allowClear="true"
           />
            -->
        <a-form-item  placeholder="请选择省市区"  >
          <JAreaSelect v-model:province="model[field]" v-model:city="model['city']" v-model:area="model['district']" />
        </a-form-item>
      </template>

      <template #storeManager="{ model, field }">
        <a-select v-model:value="model[field]" mode="tags" style="width: 100%" placeholder="请选择门店负责人"
          @click="handleOpen" :default-active-first-option="false" :show-arrow="false" :filter-option="false"
          :open="false">
        </a-select>
        <!-- <a-input @click="handleOpen" v-model:value="model[field]" placeholder="请选择门店负责人" :allowClear="true"
           /> -->
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="门店工作人员" key="xlCustomerMystore" :forceRender="true">
        <JVxeTable keep-source resizable ref="xlCustomerMystore" :loading="xlCustomerMystoreTable.loading"
          :columns="xlCustomerMystoreTable.columns" :dataSource="xlCustomerMystoreTable.dataSource" :height="340"
          :rowNumber="true" :rowSelection="true" :disabled="formDisabled" :toolbar="true">
          <!--用户-->
          <template #userName="{ value, row, rowIndex, column }">
            <a-input v-model:value="row[column.key]" mode="tags" style="width: 100%" placeholder="请选择用户"
              :disabled="formDisabled" @click="userOpen(row, rowIndex)" :default-active-first-option="false"
              :show-arrow="false" :filter-option="false" :open="false">
            </a-input>
          </template>
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 弹窗区域 -->
  <div>
    <UserSelectModal rowKey="id" @register="registerSelModal" @getSelectRowsResult="onSelectUserOk"
      :isRadioSelection="true"></UserSelectModal>
    <UserSelectModalRadio rowKey="id" @register="register1" @get-select-result="onSelectFromUserOk" />
    <typeSelModal rowKey="id" @register="registerTypeSelModal" @getSelectResult="onSelectTypeOk"
      :isRadioSelection="true"></typeSelModal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable'
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts'
import { formSchema, xlCustomerMystoreColumns } from '../XlCustomerStoreInfo.data';
import { saveOrUpdate, xlCustomerMystoreList } from '../XlCustomerStoreInfo.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils'
import { useModal } from '/@/components/Modal';
import { useMessage } from '/@/hooks/web/useMessage';
import UserSelectModal from '/@/components/Form/src/jeecg/components/modal/UserSelectModal.vue';
import UserSelectModalRadio from './UserSelectModalRadio.vue';
import typeSelModal from './typeSelModal.vue';
import JAreaSelect from '/@/components/Form/src/jeecg/components/JAreaSelect.vue';
const { createMessage } = useMessage();
const [register1, userModal ] = useModal();

const { info } = createMessage;
// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const formDisabled = ref(false);
const refKeys = ref(['xlCustomerMystore',]);
const activeKey = ref('xlCustomerMystore');
const xlCustomerMystore = ref();
const tableRefs = { xlCustomerMystore, };
const xlCustomerMystoreTable = reactive({
  loading: false,
  dataSource: [],
  columns: xlCustomerMystoreColumns
})

// const province = ref('')
// const city = ref('')
// const district = ref('')

const [registerSelModal, selModal] = useModal();
const [registerTypeSelModal, openTypeSelModal] = useModal();
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 150,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 24 }
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  formDisabled.value = !data?.showFooter;
  if (unref(isUpdate)) {
    debugger 
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    id.value = data?.record?.id
    requestSubTableData(xlCustomerMystoreList, { id: data?.record?.id }, xlCustomerMystoreTable)
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter })
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(requestAddOrEdit, classifyIntoFormData, tableRefs, activeKey, refKeys);

//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : !unref(formDisabled) ? '编辑' : '详情'));

async function reset() {
  await resetFields();
  activeKey.value = 'xlCustomerMystore';
  xlCustomerMystoreTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue)
  return {
    ...main, // 展开
    xlCustomerMystoreList: allValues.tablesValue[0].tableData,
  }
}
import { getAreaTextByCode } from '/@/components/Form/src/utils/Area';
//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    // values.province = province.value;
    // values.city = city.value;
    // values.district = district.value;
    if(values.district){
      let provinceCityDisArr = getAreaTextByCode(values.district).split("/");
      values.province = provinceCityDisArr[0];
      values.city = provinceCityDisArr[1];
      values.district = provinceCityDisArr[2];
    }
    if( values.province && values.province.length > 0 ){

    }else{
      values.province=undefined;
    }
    debugger;
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}

const id = ref();
//选择门店负责人
const handleOpen = async () => {
  var dataList = xlCustomerMystore.value?.getTableData();
  if (!!dataList.length) {
    userModal.openModal(true, {
      checkbox: false,
      modalTitle: "门店负责人选择",
      teamPeople: dataList,
      id: id.value,
    });
  } else {
    info('请先选择门店工作人员');
  }
};


const subSelIndex = ref(0)
//选择用户
function userOpen(row, rowIndex) {
  subSelIndex.value = rowIndex;
  
  //过滤的用户
  var dataList = xlCustomerMystore.value?.getTableData() || new Array();
  var filterList = new Array();
  dataList.forEach((m) => {
    filterList.push(m.userName );
  })
  selModal.openModal(true, {
    modalTitle: '选择用户',
    filterList,
  });
}

// 选择成功
async function onSelectUserOk(options, selectList, selectRows) {
  if (selectRows.value.length > 0) {
    var dataList = xlCustomerMystore.value?.getTableData();
    try {
      //赋值子表id
      selectRows.value.forEach((e, index) => {
        //表单赋值
        dataList[subSelIndex.value].userId = e.id;
        dataList[subSelIndex.value].userName = e.realname;
        dataList[subSelIndex.value].phone = e.phone

      });
      xlCustomerMystoreTable.dataSource = dataList;
    } finally {
    }
  }
}

async function onSelectFromUserOk(options, selectList, selectRows) {
  if (selectRows.value) {
    setFieldsValue({ storeManagerId: selectRows.value[0].userId });
    setFieldsValue({ storeManager: selectRows.value[0].userName });
    setFieldsValue({ storeManagerPhone: selectRows.value[0].phone });
  }
}



//选择渠道
const handleTypeOpen = async () => {
  openTypeSelModal.openModal(true, {
      modalTitle: "渠道选择",
    });
};

// 选择成功
async function onSelectTypeOk(options, selectList, selectRows) {
  if (selectList.length > 0) {
    try {
      //赋值表单值
      setFieldsValue({ 
        customerTypeCode: selectRows.value[0].typeCode, 
        customerType: selectRows.value[0].typeDesc,
        storeLevel: selectRows.value[0].level, 
      });
    } finally {
    }
  }
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>